package com.yami.shop.common.wx;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.v3.Credentials;
import com.github.binarywang.wxpay.v3.auth.AutoUpdateCertificatesVerifier;
import com.github.binarywang.wxpay.v3.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.Signer;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import springfox.documentation.service.Header;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.PrivateKey;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class HttpClientUtils {


    private static final String privateKey = "-----BEGIN PRIVATE KEY-----" +
            "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDH9i0Q1uMNKHSb\n" +
            "H+833FCl9qdvsXKvktyKckstu4w+/s5c5gvYn11YIHF7rErUluBe5p0nsWo3XGsE\n" +
            "NV8qp2ub5wcIuHTGoGcpfqFxO4MdgO15oiFHsPXggju8AeotgtQ68X012ujYWro0\n" +
            "/fXVWo/y6w+SoUvdVZ1JCMA/GoYFmuuy/Fnigf7hj0P7Bncoq7gagxvPojvikc49\n" +
            "6Lv/mLO/reseNdxt9wMm3S9oqlXVB8bqYmaLIM8XOE3kVPeePXbuJFCDfSQ5CkmV\n" +
            "f6h78Vdnh5V0l46L/Jsn0jymc+UK3bzFN1KEIO2RN71pRGcYkO4uXOqGAPrAaj5/\n" +
            "tLTqGCHvAgMBAAECggEBAMZbUtsYf0UHM5zKMfAU0b/AjNnEigLWyYVg2Wi1WesH\n" +
            "ssf+wBOUCvGnxUssX1LBlDMvyweb+8SNHe+fzhau25VcuOKSr+x1I8DKx/VeVrNG\n" +
            "uMvm4+KNDWs3ZXAb6iRZWpRaB54L2Nz+Kyb0IhAR9SfAu8L11B7slcjkMGios/gL\n" +
            "soXlqVfqITZjXIijIDN+h+GmOocawE+PCw0HezkpTAkDZ38qrI8d8hUHFBvJM+h0\n" +
            "IBPc/gGSOZWYBdcgrPQuqoONYQ8XMPQEYCzNHa5zBYqHeIg6MjKYHag/4r/gZllj\n" +
            "iX3B5180cZKf36blLnqQlb4k0N/v8ZFz6w94fOSV9xECgYEA9cynfrir3JN0kbK3\n" +
            "MZ9+wFX09Pz6x4LSW6nh/aOXRtWmM4oms7FRv15yajQbvmJaa7+bqTkfqHpaOnKY\n" +
            "8pjPva3uNzR+K2Ww7jvyNFYZ/LYW97/pEV2vv/18QIIon3EPKC95bjSQ9Pu+aqMo\n" +
            "agEyVBAhAOvd6twQnjm0qqXcIIkCgYEA0EKLyJEfepek79yYt1Dk0GuuyJEFk/xE\n" +
            "E/bsBk/sIAkO6NF37N0RQAnDn0jtDXkQa8vkFJ96zfE0bRhwYNDSN6UzT/umzPYv\n" +
            "eEGoKG3+nztyoMVExvbSxYuh+fwbtdYwhpG0N1a52K78MeLlMFW2Y9gzu895oOpd\n" +
            "eadpQq/d4LcCgYEAg502ArC3tcBvJqTfWv7gS/S62YOsdLAkG1j33Wx/UDqOaAKN\n" +
            "fqJv91yHPz7vrB3V9OQAYbhorzn0nl9GboBMnHBJod3FwU8OUkJfCo8gEyUdX0Ov\n" +
            "dNEJjnAY3CHVxqovR4FEMDKNe+BgsZDzzu8dF84bHfcuONflPhQAHW/6UqECgYEA\n" +
            "sUr1lRl2ovbWAxzZJbZIFOaXNUfAZ+sqSZS7+eOwMNWFS86HOa45MTsevktnA0E9\n" +
            "KYe585SRByGAcB+OC926GIUa2cxyg6pRXx8F+OUrDoOdYiCOHJOje2kTy61EKdje\n" +
            "FrGTqki6jizppc5zLmLJktZLtGc8NDFQwnAyvALb8KECgYB2IBzr9lpC3s/g7vVp\n" +
            "uVzviyLWGMo+6hI5XDch7rgjh/PVd5KOGp8AL9fXEO7E3PqSdJIwILJBGDvYapxw\n" +
            "Z6KKSmxWQtyKZjOwR+EP1YkbjtP9iIn95vR0Iwu7DgOiy4H2sIVMB+B7xfpU9ZpI\n" +
            "uwBnu7QwnAVHydsQuhghTYkJMA==" +
            "-----END PRIVATE KEY-----";

    // 指向自己实例的私有静态引用，主动创建
    private static HttpClientUtils httpClientUtils = new HttpClientUtils();


    // 私有的构造方法
    private HttpClientUtils(){}

    // 以自己实例为返回值的静态的公有方法，静态工厂方法
    public static HttpClientUtils getHttpClientUtils(){
        return httpClientUtils;
    }


    public static String httpPost(String param,String path,String authorization) throws IOException {
        // 定义HttpClient
        HttpPost post = null;
        String str = "";

            CloseableHttpClient httpClient = new DefaultHttpClient();
            // 设置超时时间
          //   httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);
            post = new HttpPost(path);
            // 构造消息头
            post.setHeader("Content-type", "application/json; charset=utf-8");
            post.setHeader("Connection", "Close");
            post.setHeader("Accept", "*/*");
            post.setHeader("Authorization", authorization);
            // 构建消息实体
            StringEntity entity = new StringEntity(param, Charset.forName("UTF-8"));
            entity.setContentEncoding("utf-8");
            // 发送Json格式的数据请求
            entity.setContentType("application/json");
            post.setEntity(entity);

            CloseableHttpResponse response =   httpClient.execute(post);
        try{
            HttpEntity entity2=response.getEntity();
            //EntityUtils中的toString()方法转换服务器的响应数据
            str= EntityUtils.toString(entity2, "utf-8");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            response.close();
        }

        return str;
    }


    public static String httpGet(String path,String authorization) throws IOException {
        String result="";
        try {

            URIBuilder uriBuilder = new URIBuilder(path);
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.addHeader("Accept", "application/json");
            if(StringUtils.isNotBlank(authorization)){
                httpGet.addHeader("Authorization", authorization);
            }
            HttpClient httpClient = new DefaultHttpClient();

            CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpGet);
            String bodyAsString = EntityUtils.toString(response.getEntity());
            System.out.println(bodyAsString);


            // 根据地址获取请求
//            HttpGet request = new HttpGet(path);//这里发送get请求
//            // 获取当前客户端对象
//            HttpClient httpClient = new DefaultHttpClient();
//            request.setHeader("Content-type", "application/json; charset=utf-8");
//            request.setHeader("Connection", "Close");
//            request.setHeader("Accept", "*/*");
//            request.setHeader("Authorization", authorization);
//            // 通过请求对象获取响应对象
//            HttpResponse response = httpClient.execute(request);

            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result= EntityUtils.toString(response.getEntity(),"utf-8");
            }
            result =bodyAsString;
        }catch (Exception e){
            e.printStackTrace();
        }

        return result;
    }


    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
}
